//
//  TodoDal.m
//  TodoDemo
//
//  Created by Tank on 16/3/7.
//  Copyright © 2016年 qtone. All rights reserved.
//

#import "TodoDal.h"
#import "AppDelegate.h"

@implementation TodoDal

+ (TodoModel *)insertTodoContent:(NSString *)content {
    TodoModel *todoModel = [NSEntityDescription insertNewObjectForEntityForName:@"TodoModel" inManagedObjectContext:[AppDelegate managedContext]];
    todoModel.content = content;
    todoModel.status = @(kTodoStatusProcessing);
    NSError *error;
    if (![[AppDelegate managedContext] save:&error]) {
        NSLog(@"不能保存:%@", [error description]);
        return nil;
    }
    return todoModel;
}

+ (BOOL)updateDone:(TodoModel *)todoModel {
    NSError *error;
    if (![[AppDelegate managedContext] save:&error]) {
        NSLog(@"更新失败:%@", [error description]);
        return NO;
    }
    return YES;
}

+ (BOOL)remove:(TodoModel *)todoModel {
    NSError *error;
    if (![[AppDelegate managedContext] save:&error]) {
        NSLog(@"删除失败:%@", [error description]);
        return NO;
    }
    return YES;
}

+ (NSArray *)findAllTodos {
    NSFetchRequest *fetchRequest = [NSFetchRequest new];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"TodoModel" inManagedObjectContext:[AppDelegate managedContext]];
    [fetchRequest setEntity:entity];
    NSError *error;
    NSArray *fetchedObjects = [[AppDelegate managedContext] executeFetchRequest:fetchRequest error:&error];
    NSMutableArray *processingDatas = [NSMutableArray array];
    NSMutableArray *finishedDatas = [NSMutableArray array];
    [fetchedObjects enumerateObjectsUsingBlock:^(TodoModel *obj, NSUInteger idx, BOOL *stop) {
        if ([obj.status intValue] == kTodoStatusProcessing) {
            [processingDatas addObject:obj];
        } else if ([obj.status intValue] == kTodoStatusFinished) {
            [finishedDatas addObject:obj];
        }
    }];
    return @[processingDatas, finishedDatas];
}



@end
